package xml;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;

public class MutablePropertyValues implements Iterable<PropertyValue>{
    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        propertyValueList = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        this.propertyValueList = propertyValueList != null ? propertyValueList : new ArrayList<>();
    }

    public MutablePropertyValues addPropertyValue(PropertyValue propertyValue) {
        if (null == propertyValue) {
            return this;
        }
        // 需要先判断有没有添加过,如果之前添加过,进行替换,如果没有添加过,则直接添加
        for (int i = 0; i < propertyValueList.size(); i++) {
            PropertyValue value = propertyValueList.get(i);
            if (value.getName().equals(propertyValue.getName())) {
                // 如果存在,替换
                propertyValueList.set(i, propertyValue);
                return this;
            }
        }
        propertyValueList.add(propertyValue);
        return this;
    }


    @Override
    public String toString() {
        return "MutablePropertyValues{" +
                "propertyValueList=" + propertyValueList +
                '}';
    }

    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }

    @Override
    public void forEach(Consumer<? super PropertyValue> action) {
        Iterable.super.forEach(action);
    }

    @Override
    public Spliterator<PropertyValue> spliterator() {
        return Iterable.super.spliterator();
    }
}
